package com.google.project.client.Admin;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.client.Service.UsersService;
import com.google.project.client.Service.UsersServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.UsersDTO;

public class ADMCreateProject extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField Label lblForm;
	@UiField Button btnSaveProject;
	@UiField TextBox tbProjectCode;
	@UiField TextBox tbProjectName;
	@UiField DateBox dbStartDate;
	@UiField DateBox dbDueDate;
	@UiField Button btnCancel;
	@UiField ListBox cbPJManager;
	@UiField TextBox txtLocation;
	@UiField TextBox txtConsultants;
	@UiField TextBox txtPhoneConsultants;
	@UiField TextBox txtFaxConsultant;
	@UiField TextBox txtInvestor;
	@UiField TextBox txtPhoneInvestor;
	@UiField TextBox txtFaxInvestor;
	@UiField TextArea txtDescription;
	private ProjectDTO currentProject = new ProjectDTO();
	private final ProjectServiceAsync projectService = GWT.create(ProjectService.class);
	private final UsersServiceAsync userService = GWT.create(UsersService.class);
	private List<UsersDTO> projectManagerList = new ArrayList<UsersDTO>();
	private List<ProjectDTO> pjDTOList = new ArrayList<ProjectDTO>();
	interface Binder extends UiBinder<Widget, ADMCreateProject> {
	}
	

	public ADMCreateProject() {
		initWidget(binder.createAndBindUi(this));
		dbStartDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		dbDueDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	tbProjectCode.setFocus(true);
	        }
	    });
		getAllPJ();
	}

	public ADMCreateProject(String projectId) {
		initWidget(binder.createAndBindUi(this));
		dbStartDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		dbDueDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		getProjectInfo(projectId);
	}
	
	//Lay all project dung de so sanh sau nay
	public void getAllPJ() {
		projectService.getProjectList(new AsyncCallback<List<ProjectDTO>>() {

			@Override
			public void onSuccess(List<ProjectDTO> result) {
				for(ProjectDTO pjDTO : result) {
					pjDTOList.add(pjDTO);
				}
				getCbUserName();
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Có lỗi trong quá trình Tải thông tin!");
			}
		});
	}
	
	//bind data to combobox pm
	public void getCbUserName(){
		userService.getUserList(new AsyncCallback<List<UsersDTO>>() {
			@Override
			public void onFailure(Throwable caught) {				
			}

			@Override
			public void onSuccess(List<UsersDTO> result) {
				cbPJManager.addItem("---Chọn---", "0");
				for (UsersDTO usersDTO : result) {
					if(usersDTO.getUserGroup() != null &&  usersDTO.getUserGroup() == 2){	//Chi chon ra nhung Quan tri du an
						projectManagerList.add(usersDTO);
						String display= usersDTO.getUserName()+" ("+usersDTO.getFullName()+")";
						cbPJManager.addItem(display, usersDTO.getUserId());
					}
				}
				if(currentProject.getProjectID() != null) {
					displayProject();
				}
			}
		});
		cbPJManager.setSelectedIndex(0);
	}
	public void displayProject() {
		tbProjectCode.setText(currentProject.getProjectCode());
		tbProjectCode.setEnabled(false);
		tbProjectName.setText(currentProject.getProjectName());
		int index = 0;
		for(int i = 0; i <  projectManagerList.size(); i++) {
			if(currentProject.getAccountName().equalsIgnoreCase(projectManagerList.get(i).getUserName())) {
				index = i;
			}
		}
		cbPJManager.setSelectedIndex(index + 1);
		dbStartDate.setValue(new Date(currentProject.getStartDate()));
		dbDueDate.setValue(new Date(currentProject.getDueDate()));
		txtLocation.setValue(currentProject.getLocation());
		txtConsultants.setText(currentProject.getConsultant());
		txtFaxConsultant.setText(currentProject.getFaxConsultant());
		txtPhoneConsultants.setText(currentProject.getPhoneConsultant());
		txtInvestor.setText(currentProject.getInvestor());
		txtPhoneInvestor.setText(currentProject.getPhoneInvestor());
		txtFaxInvestor.setText(currentProject.getFaxInvestor());
		txtDescription.setText(currentProject.getDescription());
		lblForm.setText("CẬP NHẬT THÔNG TIN DỰ ÁN");
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	tbProjectName.setFocus(true);
	        }
	    });
	}
	
	private void getProjectInfo(String projectId) {
		projectService.getProjectById(projectId, new AsyncCallback<ProjectDTO>() {
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Có lỗi xảy ra!");
			}

			@Override
			public void onSuccess(ProjectDTO result) {
				currentProject = result;
				getAllPJ();
			}
		});
	}
	
	/***
	 * 
	 * add new project to database
	 */
	@UiHandler("btnSaveProject")
	void onBtnSaveProjectClick(ClickEvent event) {
		if(validateData()) {
			currentProject.setProjectCode(tbProjectCode.getText());
			currentProject.setProjectName(tbProjectName.getText());
			currentProject.setStartDate(dbStartDate.getValue().getTime());
			currentProject.setDueDate(dbDueDate.getValue().getTime());
			currentProject.setUserId(cbPJManager.getValue(cbPJManager.getSelectedIndex()));
			String pmName=cbPJManager.getItemText(cbPJManager.getSelectedIndex());
			currentProject.setAccountName(pmName.split(" ")[0]);
			currentProject.setLocation(txtLocation.getText());
			currentProject.setConsultant(txtConsultants.getText());
			currentProject.setFaxConsultant(txtFaxConsultant.getText());
			currentProject.setPhoneConsultant(txtPhoneConsultants.getText());
			currentProject.setInvestor(txtInvestor.getText());
			currentProject.setPhoneInvestor(txtPhoneInvestor.getText());
			currentProject.setFaxInvestor(txtFaxInvestor.getText());
			currentProject.setDescription(txtDescription.getText());
			if (currentProject.getProjectID() == null) {
				currentProject.setStatus(0);
				projectService.addProject(currentProject, new AsyncCallback<ProjectDTO>() {
							@Override
							public void onSuccess(ProjectDTO result) {
								Window.alert("Thêm mới thành công!");
								ADMEntrypoint.get().ADMProjectList();
							}
	
							@Override
							public void onFailure(Throwable caught) {
								Window.alert("Có lỗi xảy ra!");
							}
						});
			} else {
				projectService.updateProject(currentProject, new AsyncCallback<Void>() {
	
					@Override
					public void onSuccess(Void result) {
						Window.alert("Cập nhật thành công!");
						ADMEntrypoint.get().ADMProjectList();
					}
	
					@Override
					public void onFailure(Throwable caught) {
						Window.alert("Có lỗi xảy ra!");
					}
				});
			}
		}
	}
	
	//Ham kiem soat cac du lieu nhap vao
	public boolean validateData() {
		String pjCode = tbProjectCode.getText();
		String pjName = tbProjectName.getText();
		String pjManager = cbPJManager.getValue(cbPJManager.getSelectedIndex());
		Date toDay = new Date();
		
		//Validate Project Code
		if(pjCode == null || pjCode.equals("")) {
			Window.alert("Bạn phải nhập Mã dự án!");
			Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
		        public void execute () {
		        	tbProjectCode.setFocus(true);
		        }
		    });
			return false;
		} else {
			if(currentProject.getProjectID() == null) {
				for(ProjectDTO pjDTO : pjDTOList) {
					if(pjDTO.getProjectCode().equals(pjCode)) {
						Window.alert("Mã dự án này đã tồn tại! Hãy nhập Mã khác!");
						Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
					        public void execute () {
					        	tbProjectCode.setFocus(true);
					        }
					    });
						return false;
					}
				} 
			}
		}
		
		//Validate Project Name
		if(pjName == null || pjName.equals("")) {
			Window.alert("Bạn phải nhập Tên dự án!");
			Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
		        public void execute () {
		        	tbProjectName.setFocus(true);
		        }
		    });
			return false;
		}
		
		//Validate Project Manager
		if(pjManager.equals("0")) {
			Window.alert("Bạn phải chọn Quản trị dự án!");
			Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
		        public void execute () {
		        	cbPJManager.setFocus(true);
		        }
		    });
			return false;
		}
		
		//Validate Time
		if(dbStartDate.getValue() == null || dbStartDate.getValue().equals("")) {
			Window.alert("Bạn phải nhập thời gian!");
			Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
		        public void execute () {
		        	dbStartDate.setFocus(true);
		        }
		    });
			return false;
		} else if(dbDueDate.getValue() == null || dbDueDate.getValue().equals("")) {
			Window.alert("Bạn phải nhập thời gian!");
			Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
		        public void execute () {
		        	dbDueDate.setFocus(true);
		        }
		    });
			return false;
		} else {
			Date _fromDate = dbStartDate.getValue();
			Date _toDate = dbDueDate.getValue();
			int check1 = CommonFuntion.compareWithTwoDay(_fromDate, toDay);
			int check2 = CommonFuntion.compareWithTwoDay(_fromDate, _toDate);
			int check3 = CommonFuntion.compareWithTwoDay(_toDate, toDay);
			if(currentProject.getProjectID() == null) {
				currentProject.setStartDate(0L);
				currentProject.setDueDate(0L);
			}
//			if((dbStartDate.getValue().getTime() != currentProject.getStartDate()) && (check1 == 1)) {
//					Window.alert("Bạn phải nhập thời gian Từ ngày lớn hơn hoặc bằng ngày hiện tại!");
//					Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
//				        public void execute () {
//				        	dbStartDate.setFocus(true);
//				        }
//				    });
//					return false;
//			}
//			
//			if((dbDueDate.getValue().getTime() != currentProject.getDueDate()) && (check3 == 1)) {
//				Window.alert("Bạn phải nhập thời gian Đến ngày lớn hơn hoặc bằng ngày hiện tại!");
//				Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
//			        public void execute () {
//			        	dbDueDate.setFocus(true);
//			        }
//			    });
//				return false;
//			}
			if(check2 == 2) {
				Window.alert("Bạn phải nhập thời gian Từ ngày nhỏ hơn hoặc bằng thời gian Đến ngày!");
				Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
			        public void execute () {
			        	dbStartDate.setFocus(true);
			        }
			    });
				return false;
			}
		}
		return true;
	}

	@UiHandler("btnCancel")
	void onBtnCancelClick(ClickEvent event) {
		ADMEntrypoint.get().ADMProjectList();
	}
}
